package com.company.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.company.project.common.exception.BusinessException;
import com.company.project.common.exception.code.BaseResponseCode;
import com.company.project.common.utils.DataResult;
import com.company.project.entity.*;
import com.company.project.mapper.SysRoleMapper;
import com.company.project.mapper.SysUserRoleMapper;
import com.company.project.service.*;
import com.company.project.vo.req.store.CheckStoreReqVO;
import com.company.project.vo.req.store.StoreRegisterReqVO;
import com.company.project.vo.resp.store.RegisterRespVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.company.project.mapper.SysStoreMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service("sysStoreService")
@Slf4j
public class SysStoreServiceImpl extends ServiceImpl<SysStoreMapper, SysStoreEntity> implements SysStoreService {
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private SysAreaService sysAreaService;
    @Autowired(required = false)
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired(required = false)
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private HttpSessionService httpSessionService;
    @Override
    public RegisterRespVO register(StoreRegisterReqVO vo) {
        return this.register(vo,4);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RegisterRespVO register(StoreRegisterReqVO vo, Integer status) {
        String password = "1234567890";
        //  用户信息，门店信息，注册门店。
        // 1. 记录用户信息。
        com.company.project.vo.req.RegisterReqVO register = new com.company.project.vo.req.RegisterReqVO();
        register.setUsername(vo.getPhone());            // 用户名
        register.setPassword(vo.getPhone());            // 密码
        register.setPhone(vo.getPhone());               // 手机号
        register.setRealName(vo.getRealName());         // 用户名
        register.setNickName(vo.getRealName());         // 昵称
        register.setSex(vo.getSex());                   // 性别
        register.setPassword(password);                 // 默认密码
        String userId = userService.register(register);

        // 2.赋予用户角色
        QueryWrapper queryRole = new QueryWrapper();
        queryRole.eq("name","门店角色");
        SysRole sysRole = sysRoleMapper.selectOne(queryRole);
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(userId);
        sysUserRole.setRoleId(sysRole.getId());
        sysUserRoleMapper.insert(sysUserRole);

        // 3. 记录门店信息。
        SysStoreEntity sysStore = new SysStoreEntity();
        sysStore.setDeptId(deptService.rootDept());
        sysStore.setUserId(userId);                     // 用户id
        sysStore.setLicense(vo.getLicense());           // 营业执照
        sysStore.setProvince(vo.getProvince());         // 省
        sysStore.setCity(vo.getCity());                 // 市
        sysStore.setArea(vo.getArea());                 // 区
        sysStore.setAddress(vo.getAddress());           // 地址
        sysStore.setStoreName(vo.getStoreName());       // 全称
        sysStore.setStoreNames(vo.getStoreNames());     // 简称
        sysStore.setLng(vo.getLng());                   // 经度
        sysStore.setMlat(vo.getMlat());                 // 纬度
        sysStore.setStatus(status);                     // 门店状态（1.正常2.停用 3.审核失败 4.审核中） // 门店提交注册；
        sysStore.setCreateTime(new Date());
        sysStore.setStoreMsg(vo.getStoreMsg()); //
        boolean i = this.save(sysStore);
        if (!i) {
            throw new BusinessException(BaseResponseCode.OPERATION_ERRO);
        }
        // 3. 返回用户信息，门店信息
        RegisterRespVO res = new RegisterRespVO();
        res.setPhone(vo.getPhone());
        res.setPassword(password);
        res.setRealName(vo.getRealName());
        res.setSex(vo.getSex());
        res.setStoreId(sysStore.getId());
        res.setStoreName(sysStore.getStoreName());
        res.setStoreNames(sysStore.getStoreNames());
        return res;
    }

    @Override
    public boolean statusUpdate(CheckStoreReqVO vo) {
        SysStoreEntity sysStore = new SysStoreEntity();
        sysStore.setId(vo.getId());
        sysStore.setStatus(vo.getStatus());
        sysStore.setErrorMsg(vo.getErrorMsg());
        return this.updateById(sysStore);
//        return false;
    }

    @Override
    public IPage<SysStoreEntity> storeArea(IPage<SysStoreEntity> iPage) {
        List<SysStoreEntity> list = iPage.getRecords();
        for(int i = 0 ; i < list.size(); i++){
            QueryWrapper province = new QueryWrapper();
            province.eq("id",list.get(i).getProvince());
            SysAreaEntity area1 = sysAreaService.getOne(province);
            list.get(i).setProvince(area1.getAreaCode()+","+area1.getAreaName());

            QueryWrapper city = new QueryWrapper();
            city.eq("id",list.get(i).getCity());
            SysAreaEntity area2 = sysAreaService.getOne(city);
            list.get(i).setCity(area2.getAreaCode()+","+area2.getAreaName());

            QueryWrapper area = new QueryWrapper();
            area.eq("id",list.get(i).getArea());
            SysAreaEntity area3 = sysAreaService.getOne(area);
            list.get(i).setArea(area3.getAreaCode()+","+area3.getAreaName());
        }
        iPage.setRecords(list);
        return iPage;
    }

    @Override
    public SysStoreEntity checkStore(String storeId) {
        SysStoreEntity sysStoreEntity ;
        // 查询条件
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",storeId);
        queryWrapper.eq("dept_id","deptService.rootDept()");
        sysStoreEntity = super.getOne(queryWrapper);
        // 返回查询结果
        return sysStoreEntity;
    }

    @Override
    public SysStoreEntity getMyStoreInfo() {
        // 获取当前用户信息
        SysUser sysUser= httpSessionService.getCurrentUserInfo();
        // 查询用户门店
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", sysUser.getId());
        SysStoreEntity sysStoreEntity = super.getOne(queryWrapper);
        //返回门店信息
        return sysStoreEntity;
    }


}